<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="工序编号" prop="procedureCode">
        <el-input v-model="queryParams.procedureCode" placeholder="请输入工序编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="工序名称" prop="procedureName">
        <el-input v-model="queryParams.procedureName" placeholder="请输入工序名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="质检方案编码" prop="schemeCode">
        <el-input v-model="queryParams.schemeCode" placeholder="请输入质检方案编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="质检方案名称" prop="schemeName">
        <el-input v-model="queryParams.schemeName" placeholder="请输入质检方案名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="质检方式" prop="schemeMethod">
        <el-select v-model="queryParams.schemeMethod" filterable placeholder="请选择质检方式" clearable
                   size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SCHEME_METHOD)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="质检类型" prop="schemeType">
        <el-select v-model="queryParams.schemeType" filterable placeholder="请选择质检类型" clearable
                   size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SCHEME_TYPE)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['quality:inspection-scheme:create']">新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['quality:inspection-scheme:export']">导出
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['quality:inspection-scheme:delete']"
        >
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="质检方案名称" align="center" prop="schemeName" width="150" show-overflow-tooltip/>
      <el-table-column label="质检方案编码" align="center" prop="schemeCode" width="150" show-overflow-tooltip/>
      <el-table-column label="产品名称" align="center" prop="productName" width="250" show-overflow-tooltip/>
      <el-table-column label="产品编码" align="center" prop="productCode" width="150" show-overflow-tooltip/>
      <el-table-column label="工序编号" align="center" prop="procedureCode" width="150" show-overflow-tooltip/>
      <el-table-column label="工序名称" align="center" prop="procedureName" width="150" show-overflow-tooltip/>
      <el-table-column label="质检方式" align="center" prop="schemeMethod" width="150">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.SCHEME_METHOD, scope.row.schemeMethod) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="质检类型" align="center" prop="schemeType">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.SCHEME_TYPE, scope.row.schemeType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="巡检间隔(min)" align="center" prop="intervalTime" width="150" />
      <el-table-column label="抽检比例/数量" align="center" prop="samplingRatio" width="150" />
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['quality:inspection-scheme:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-setting" @click="configSchemeItems(scope.row)"
                     v-hasPermi="['quality:inspection-scheme:update']">配置质检项
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['quality:inspection-scheme:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <InspectionSchemeForm ref="formRef" @success="getList"/>

    <!-- 质检项配置对话框 -->
    <el-dialog title="质检项配置" :visible.sync="schemeItemsVisible" width="1500px" v-dialogDrag append-to-body>
      <div class="mb-2" style="text-align: right;">
        <el-button type="primary" size="mini" style="float: right; margin-bottom: 10px;" @click="showAddItemDialog">
          添加质检项
        </el-button>
      </div>
      <el-table
        v-loading="schemeItemsLoading"
        :data="schemeItemsList"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleSchemeItemCheckboxChange"
        height="500px"
      >
        <el-table-column type="selection" width="55" fixed="left"/>
        <el-table-column label="质检项名称" align="center" prop="itemName" width="150" fixed="left" />
        <el-table-column label="质检项分类" align="center" prop="itemType" width="120">
          <template v-slot="scope">
            <span>{{ getDictDataLabel(DICT_TYPE.QUALITY_INSPECTION_SCHEME_ITEM_TYPE, scope.row.itemType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数值类型" align="center" prop="itemDataType" width="100">
          <template v-slot="scope">
            {{ getMapLabel(scope.row.itemDataType, itemDataTypeMap) }}
          </template>
        </el-table-column>
        <el-table-column label="录入方式" align="center" prop="inputMethod" width="100">
          <template v-slot="scope">
            {{ getMapLabel(scope.row.inputMethod, inputMethodMap) }}
          </template>
        </el-table-column>
        <el-table-column label="标准值" align="center" prop="otherDefect" width="100" />
        <el-table-column label="上公差" align="center" prop="upperValue" width="80" />
        <el-table-column label="下公差" align="center" prop="lowerValue" width="80" />
        <el-table-column label="下警戒值" align="center" prop="lowerBias" width="90" />
        <el-table-column label="上警戒值" align="center" prop="upperBias" width="90" />
        <el-table-column label="SPC坐标" align="center" prop="excelCoordinate" width="90" />
        <el-table-column label="检验默认值" align="center" prop="defaultValue" width="100" />
        <el-table-column label="SPC检" align="center" prop="spcInspection" width="80" />
        <el-table-column label="全尺寸检" align="center" prop="fullSizeInspection" width="100" />
        <el-table-column label="全尺寸坐标" align="center" prop="fullSizeCoordinate" width="110" />
        <el-table-column label="量具坐标" align="center" prop="toolCoordinate" width="90" />
        <el-table-column label="文件名称代码" align="center" prop="failNameCode" width="120" />
        <el-table-column label="不良判定方式" align="center" prop="defectMethod" width="120">
          <template v-slot="scope">
            {{ getMapLabel(scope.row.defectMethod, defectMethodMap) }}
          </template>
        </el-table-column>
        <el-table-column label="不良原因" align="center" prop="badReasons" width="120" />
        <el-table-column label="备注" align="center" prop="memo" width="150" />
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="showEditItemDialog(scope.row)"/>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteSchemeItem(scope.$index)"/>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="schemeItemsVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加质检项对话框 -->
    <el-dialog title="选择质检项" :visible.sync="addItemVisible" width="600px" v-dialogDrag append-to-body>
      <el-form :model="addItemForm" ref="addItemFormRef" label-width="100px">
        <el-form-item label="质检项" prop="schemeItemId">
          <el-select v-model="addItemForm.schemeItemId" placeholder="请选择质检项" style="width: 100%" filterable remote
                     :remote-method="remoteMethod" :loading="loading">
            <el-option
              v-for="item in filteredSchemeItems && filteredSchemeItems.length > 0 ? filteredSchemeItems : allSchemeItems"
              :key="item.id" :label="item.itemName" :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addItemVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddItem">确认</el-button>
      </div>
    </el-dialog>

    <!-- 编辑质检项对话框 -->
    <el-dialog title="编辑质检项" :visible.sync="editItemVisible" width="1000px" v-dialogDrag append-to-body>
      <el-form :model="schemeItemsRow" ref="editItemFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="质检项名称" prop="itemName">
              <el-input v-model="schemeItemsRow.itemName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标准值" prop="otherDefect">
              <el-input v-model="schemeItemsRow.otherDefect"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上公差" prop="upperValue">
              <el-input v-model="schemeItemsRow.upperValue"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="下公差" prop="lowerValue">
              <el-input v-model="schemeItemsRow.lowerValue"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下警戒值" prop="lowerBias">
              <el-input v-model="schemeItemsRow.lowerBias"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上警戒值" prop="upperBias">
              <el-input v-model="schemeItemsRow.upperBias"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="SPC坐标" prop="excelCoordinate">
              <el-input v-model="schemeItemsRow.excelCoordinate"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检验默认值" prop="defaultValue">
              <el-input v-model="schemeItemsRow.defaultValue"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="SPC检" prop="spcInspection">
              <el-input v-model="schemeItemsRow.spcInspection"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="全尺寸检" prop="fullSizeInspection">
              <el-input v-model="schemeItemsRow.fullSizeInspection"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="全尺寸坐标" prop="fullSizeCoordinate">
              <el-input v-model="schemeItemsRow.fullSizeCoordinate"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="量具坐标" prop="toolCoordinate">
              <el-input v-model="schemeItemsRow.toolCoordinate"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="不良原因" prop="badReasons">
              <el-input v-model="schemeItemsRow.badReasons"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="schemeItemsRow.memo" type="textarea" rows="2"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editItemVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEditItem">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as InspectionSchemeApi from '@/api/quality/inspectionscheme/index.js';
import * as InspectionSchemeItemApi from '@/api/quality/inspectionschemeitem/index.js';
import * as SchemeItemApi from '@/api/quality/schemeitem/index.js';
import InspectionSchemeForm from './InspectionSchemeForm.vue';
import { getDictDatas,getDictDataLabel, DICT_TYPE } from '@/utils/dict'

export default {
  name: "InspectionScheme",
  components: {
    InspectionSchemeForm,
  },
  data() {
    return {
      rowInfo: {},
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 质检方案列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        productId: null,
        productName: null,
        productCode: null,
        processId: null,
        procedureCode: null,
        procedureName: null,
        schemeCode: null,
        schemeName: null,
        schemeMethod: null,
        schemeType: null,
        status: null,
        createTime: [],
      },
      // 质检项配置相关
      schemeItemsVisible: false,
      schemeItemsLoading: false,
      schemeItemsList: [],
      currentSchemeId: null,
      schemeItemCheckedIds: [],
      // 质检项编辑相关
      editItemVisible: false,
      schemeItemsRow: {},
      // 添加质检项相关
      addItemVisible: false,
      addItemForm: {
        schemeItemId: null
      },
      allSchemeItems: [],
      // 过滤后的质检项
      filteredSchemeItems: [],
      // 数值类型映射数组
      itemDataTypeMap: [
        {value: '1', label: '字符(外观)'},
        {value: '2', label: '数字'},
        {value: '3', label: '日期'},
        {value: '4', label: '是/否'},
        {value: '5', label: '字符(功能)'}
      ],
      // 录入方式映射数组
      inputMethodMap: [
        {value: '0', label: '无'},
        {value: '1', label: '手工录入'},
        {value: '2', label: '按标准值校验'}
      ],
      // 不良判定方式映射数组
      defectMethodMap: [
        {value: '0', label: '无'},
        {value: '1', label: '手工输入'},
        {value: '2', label: '枚举选择'}
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await InspectionSchemeApi.getInspectionSchemePage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除质检?')
      try {
        await InspectionSchemeApi.deleteInspectionScheme(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除质检方案 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await InspectionSchemeApi.deleteInspectionSchemeList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有质检方案数据项?');
      try {
        this.exportLoading = true;
        const data = await InspectionSchemeApi.exportInspectionSchemeExcel(this.queryParams);
        this.$download.excel(data, '质检方案.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },

    /** 配置质检项 */
    configSchemeItems(schemeRow) {
      this.currentSchemeId = schemeRow.id;
      this.rowInfo = {...schemeRow}
      // 从行内获取inspectionSchemeItemList字段，如果没有则为空数组
      this.schemeItemsList = schemeRow.inspectionSchemeItemList || [];
      console.log('行内获取质检项列表:', this.schemeItemsList)
      this.schemeItemsVisible = true;
    },

    /** 处理质检项选择变化 */
    handleSchemeItemCheckboxChange(records) {
      this.schemeItemCheckedIds = records.map((item) => item.id);
    },

    /** 显示添加质检项对话框 */
    async showAddItemDialog() {
      this.addItemForm.schemeItemId = null;
      await this.getAllSchemeItems();
      this.addItemVisible = true;
    },

    /** 远程搜索方法 */
    async remoteMethod(query) {
      if (query === '') {
        this.filteredSchemeItems = [];
        return;
      }

      this.loading = true;
      try {
        // 调用接口搜索质检项，使用itemName作为参数
        const response = await SchemeItemApi.getSchemeItemPage({
          itemName: query,
          pageNum: 1,
          pageSize: 100 // 适当设置分页大小，满足下拉框展示需求
        });
        console.log('搜索质检项返回:', response);
        // 将搜索结果赋值给过滤后的质检项数组
        this.filteredSchemeItems = response.data.list
      } catch (error) {
        console.error('搜索质检项失败:', error);
        this.filteredSchemeItems = [];
      } finally {
        this.loading = false;
      }
    },

    /** 获取所有质检项列表 */
    async getAllSchemeItems() {
      try {
        const res = await SchemeItemApi.getSchemeItemPage({
          pageNo: 1,
          pageSize: 100
        });
        this.allSchemeItems = res.data.list || [];
      } catch (error) {
        this.$modal.msgError('获取质检项列表失败');
      }
    },

    /** 确认添加质检项 */
    async confirmAddItem() {
      if (!this.addItemForm.schemeItemId) {
        this.$modal.msgError('请选择质检项');
        return;
      }

      try {
        // 查找对应的质检方案对象
        const schemeItem = this.allSchemeItems.find(item => item.id === this.addItemForm.schemeItemId);
        if (!schemeItem) {
          this.$modal.msgError('未找到选中的质检项');
          return;
        }

        delete schemeItem.id;

        // // 检查是否已存在该质检项
        // const exists = this.schemeItemsList.some(item => item.schemeItemId === this.addItemForm.schemeItemId);
        // if (exists) {
        //   this.$modal.msgError('该质检项已存在');
        //   return;
        // }

        // 创建新的质检项关联对象
        const newItem = {
          inspectionSchemeId: this.currentSchemeId,
          schemeItemId: this.addItemForm.schemeItemId,
          // 复制质检项的属性到关联对象中
          ...schemeItem
        };

        // 临时创建包含新项的列表用于API调用
        const tempSchemeItemsList = [...this.schemeItemsList, newItem];

        // 准备更新数据
        const updateData = {
          ...this.rowInfo,
          inspectionSchemeItemList: tempSchemeItemsList
        };

        // 调用编辑接口保存（只有成功后才会更新本地列表）
        await InspectionSchemeApi.updateInspectionScheme(updateData);

        // API调用成功后，才将新项添加到列表中
        this.schemeItemsList.push(newItem);

        // 查找当前方案在列表中的位置
        const schemeIndex = this.list.findIndex(item => item.id === this.currentSchemeId);
        if (schemeIndex !== -1) {
          // 更新列表中的方案对象
          this.list[schemeIndex].inspectionSchemeItemList = [...this.schemeItemsList];

          // 重新获取最新的质检项列表
          const result = await InspectionSchemeApi.getInspectionScheme(this.currentSchemeId);
          console.log(result,'resultresult')
          if (result && result.data && result.data.inspectionSchemeItemList) {
            this.schemeItemsList = result.data.inspectionSchemeItemList;
          }

          this.$modal.msgSuccess('添加成功');
          this.addItemVisible = false;
        } else {
          this.$modal.msgError('未找到对应的质检方案');
        }
      } catch (error) {
      }
    },

    /** 删除质检项 */
    async deleteSchemeItem(index) {
      await this.$modal.confirm('是否确认删除该质检项?');
      try {
        // 从列表中删除
        this.schemeItemsList.splice(index, 1);

        // 查找当前方案在列表中的位置
        const schemeIndex = this.list.findIndex(item => item.id === this.currentSchemeId);
        if (schemeIndex !== -1) {
          // 更新列表中的方案对象
          this.list[schemeIndex].inspectionSchemeItemList = [...this.schemeItemsList];

          // 准备更新数据
          const updateData = {
            ...this.list[schemeIndex],
            inspectionSchemeItemList: this.schemeItemsList
          };

          // 调用编辑接口保存
          await InspectionSchemeApi.updateInspectionScheme(updateData);

          // 重新获取最新的质检项列表
          const result = await InspectionSchemeApi.getInspectionScheme(this.currentSchemeId);
          if (result && result.data && result.data.inspectionSchemeItemList) {
            this.schemeItemsList = result.data.inspectionSchemeItemList;
          }

          this.$modal.msgSuccess('删除成功');
        } else {
          this.$modal.msgError('未找到对应的质检方案');
        }
      } catch (error) {
        this.$modal.msgError('删除失败');
      }
    },

    /** 显示编辑质检项对话框 */
    showEditItemDialog(row) {
      // 深拷贝选中的行数据，避免直接修改表格数据
      this.schemeItemsRow = { ...row };
      this.editItemVisible = true;
    },

    /** 确认编辑质检项 */
    async confirmEditItem() {
      try {
        // 查找当前编辑的质检项在列表中的位置
        const index = this.schemeItemsList.findIndex(item => item.schemeItemId === this.schemeItemsRow.schemeItemId);
        if (index !== -1) {
          // 更新列表中的质检项数据
          this.schemeItemsList[index] = { ...this.schemeItemsRow };

          // 查找当前方案在列表中的位置
          const schemeIndex = this.list.findIndex(item => item.id === this.currentSchemeId);
          if (schemeIndex !== -1) {
            // 更新列表中的方案对象
            this.list[schemeIndex].inspectionSchemeItemList = [...this.schemeItemsList];

            // 准备更新数据
            const updateData = {
              ...this.list[schemeIndex],
              inspectionSchemeItemList: this.schemeItemsList
            };

            // 调用编辑接口保存
            await InspectionSchemeApi.updateInspectionScheme(updateData);

            // 重新获取最新的质检项列表
            const result = await InspectionSchemeApi.getInspectionScheme(this.currentSchemeId);
            if (result && result.data && result.data.inspectionSchemeItemList) {
              this.schemeItemsList = result.data.inspectionSchemeItemList;
            }

            this.$modal.msgSuccess('保存成功');
            this.editItemVisible = false;
          } else {
            this.$modal.msgError('未找到对应的质检方案');
          }
        } else {
          this.$modal.msgError('未找到对应的质检项');
        }
      } catch (error) {
        this.$modal.msgError('保存失败');
      }
    },

    /** 获取映射标签 */
    getMapLabel(value, mapArray) {
      const item = mapArray.find(item => item.value === value);
      return item ? item.label : value;
    },
  }
};
</script>
